package com.sy.simpleegg.platform.lyysdk.handler

import com.google.gson.Gson
import com.sy.simpleegg.ext.logFile
import com.sy.simpleegg.platform.lyysdk.ShowStyle
import com.sy.simpleegg.platform.lyysdk.bean.LyySdkGoodBean
import com.sy.logger.Logger
import com.sy.nettyclient.common.constant.ActionCode
import com.sy.nettyclient.common.param.ReplyCheckEqParam
import com.sy.nettyclient.common.param.parent.BaseParam
import com.sy.nettyclient.common.response.ErrorResp
import com.sy.nettyclient.common.response.LoginResp
import com.sy.nettyclient.common.response.PayCodeResp
import com.sy.nettyclient.common.response.QrCodeResp
import com.sy.nettyclient.common.response.ResponseParam
import com.sy.nettyclient.msg.MsgProducer
import com.sy.nettyclient.msg.handler.AbstractMsgHandler
import com.sy.vendingmachine.platform.lyysdk.ShowType
import org.json.JSONObject

class LyyMsgHandler(
    callback:OnNettyCallback?
): AbstractMsgHandler() {

    private val TAG = javaClass.simpleName

    private var onNettyCallback: OnNettyCallback? = null

    private var devNumber: String? = null

    private var loginFailedCount = 0

    init {
        onNettyCallback = callback
    }

    /**
     * 设备登录
     * @param responseParam
     * @return
     */
    override fun loginHandler(responseParam: ResponseParam?): Boolean {
        super.loginHandler(responseParam)
        responseParam?.let {
            try {
                val resp = getResp(responseParam, LoginResp::class.java)
                //        System.out.println(String.format("get 设备登录结果为：%s", gson.toJson(resp)));
                logFile("lyy-登录结果：" + gson.toJson(resp))
                val d = resp.d
                when (d) {
                    "0" -> {
                        onNettyCallback?.onLoginSuccess(resp.v)
                    }

                    "1" -> {
                        //设备未绑定
                        val q = resp.q
                        devNumber = resp.v
                        onNettyCallback?.showRegist(ShowType.SHOW, q)
                    }

                    else -> {}
                }
            }catch (e: Exception){
                e.printStackTrace()
                loginFailedCount ++
                logFile("登录异常 第${loginFailedCount}次：${e.message}")
                if (loginFailedCount < 3){
                    MsgProducer.getSignRandom(null)
                }else{

                }
            }
        }?:{
            loginFailedCount ++
            if (loginFailedCount < 3){
                MsgProducer.getSignRandom(null)
            }else{

            }
        }

        return true
    }

    /**
     * 设备注册二维码
     * @param responseParam
     * @return
     */
    override fun qrCodeHandler(responseParam: ResponseParam?): Boolean {
        super.qrCodeHandler(responseParam)
        responseParam?.let {
            val resp = getResp(it, QrCodeResp::class.java)
            logFile("lyy-设备注册二维码：" + gson.toJson(resp))
            onNettyCallback?.showRegist(ShowType.SHOW, resp.d)
        }
        return true
    }

    /**
     * 设备绑定
     * @param responseParam
     * @return
     */
    override fun eqBindNoticeHandler(responseParam: ResponseParam?): Boolean {
        super.eqBindNoticeHandler(responseParam)
        responseParam?.let {
            onNettyCallback?.showRegist(ShowType.HIDE, null)
            onNettyCallback?.onLoginSuccess(devNumber)
        }
        return true
    }

    /**
     * 设备解绑
     * @param responseParam
     * @return
     */
    override fun eqUnBindNoticeHandler(responseParam: ResponseParam?): Boolean {
        super.eqUnBindNoticeHandler(responseParam)
        responseParam?.let {
            onNettyCallback?.showRegist(ShowType.OTHER, null)
        }
        return true
    }

    /**
     * 支付二维码
     * @param responseParam
     * @return
     */
    override fun payCodeHandler(responseParam: ResponseParam?): Boolean {
        super.payCodeHandler(responseParam)
        responseParam?.let {
            val resp = getResp(it, PayCodeResp::class.java)
            logFile("lyy-支付二维码：" + gson.toJson(resp))
            val payCodeData = resp.d
            onNettyCallback?.showPayCode(payCodeData, ShowStyle.QRCODE)
        }
        return true
    }

    /**
     * 支付结果
     * @param responseParam
     * @return
     */
    override fun payResultHandler(responseParam: ResponseParam?): Boolean {
        super.payResultHandler(responseParam)
        responseParam?.let {
//            val resp = getResp(responseParam, ResponseParam::class.java)fgfg
            logFile("lyy-支付结果：" + gson.toJson(responseParam))
            val k = responseParam.k
//            payResultVerify?.let {
//                when (it.invoke(k)) {
//                    true -> {
//                        callback?.receiveOrder(k)
//                    }
//                    false -> {
//                        callback?.refund(k)
//                    }
//                }
//            }?:{
//                //设备启动失败，退款
//                callback?.refund(k)
//            }
        }
        return true
    }

    /**
     * 设备启动结果上报
     * @param responseParam
     * @return
     */
    override fun eqStartResultReHandler(responseParam: ResponseParam?): Boolean {
        println(String.format("get 设备启动结果上传返回结果为：%s", gson.toJson(responseParam)))
        return true
    }

    override fun reportEquipmentFailureResultHandler(responseParam: ResponseParam?): Boolean {
        println(String.format("上报设备错误信息 结果返回：%s", gson.toJson(responseParam)))
        return true
    }

    override fun reportReversePayInfoResultHandler(responseParam: ResponseParam?): Boolean {
        return super.reportReversePayInfoResultHandler(responseParam)
    }

    /**
     * 上报iccid
     * @param responseParam
     * @return
     */
    override fun reportICCIDResultHandler(responseParam: ResponseParam?): Boolean {
        return super.reportICCIDResultHandler(responseParam)
    }

    /**
     * 位置信息
     * @param responseParam
     * @return
     */
    override fun gpsHandler(responseParam: ResponseParam?): Boolean {
        super.gpsHandler(responseParam)
        //        ReplyGpsParam param = new ReplyGpsParam();
//        param.setUniqueCode(responseParam.getK());
//        param.setLongitude("113.38795");
//        param.setLatitude("22.9753936");
//        MsgProducer.replyGps(param);
        return true
    }

    override fun queryAdsHandler(responseParam: ResponseParam?): Boolean {
        return super.queryAdsHandler(responseParam)
//        ReplyQueryAdsParam param = new ReplyQueryAdsParam();
//        param.setUniqueCode(responseParam.getK());
//        param.setType("1");
//        param.setScreenWidth(100);
//        param.setScreenHeight(100);
//        param.setResolutionWidth(6700);
//        param.setResolutionHeight(4000);
//
//        List<AdsPosition> positions = new ArrayList<>();
//        AdsPosition position1 = new AdsPosition();
//        position1.setValue("left0010");
//        position1.setName("左广告位");
//        position1.setArea("(0,0),(10,10)");
//        position1.setWidth(10);
//        position1.setHeight(10);
//        position1.setIsFullScreen("N");
//        position1.setScreenType("V");
//
//        AdsPosition position2 = new AdsPosition();
//        position2.setValue("right0010");
//        position2.setName("右广告位");
//        position2.setArea("(10,10),(60,60)");
//        position2.setWidth(40);
//        position2.setHeight(40);
//        position2.setIsFullScreen("N");
//        position2.setScreenType("H");
//
//        positions.add(position1);
//        positions.add(position2);
//        param.setPositions(positions);
//        return MsgProducer.replyQueryAds(param);
    }

    override fun sendAdsHandler(responseParam: ResponseParam?): Boolean {
        return super.sendAdsHandler(responseParam)
//        BaseParam param = new BaseParam();
//        param.setUniqueCode(responseParam.getK());
//        return MsgProducer.replySendAds(param);
    }

    override fun uploadAdsResultHandler(responseParam: ResponseParam?): Boolean {
        return super.uploadAdsResultHandler(responseParam)
    }

    override fun updateAdsHandler(responseParam: ResponseParam): Boolean {
        super.updateAdsHandler(responseParam)
        val param = BaseParam()
        param.uniqueCode = responseParam.k
        return MsgProducer.replyUpdateAds(param)
    }

    /**
     * 启动设备
     * @param responseParam
     * @return
     */
    override fun startEquipmentHandler(responseParam: ResponseParam): Boolean {
        super.startEquipmentHandler(responseParam)
        try {
            val startKey = responseParam.k
            val jsonStr = gson.toJson(responseParam.p)
            var coins = ""
            var money = ""
            var unique = ""
            val jsonObject = JSONObject(jsonStr)
            if (jsonObject.has("coins")) {
                coins = jsonObject.getString("coins")
            }
            if (jsonObject.has("payAmount")) {
                money = jsonObject.getString("payAmount")
            }
            if (jsonObject.has("unique")) {
                unique = jsonObject.getString("unique")
            }
            onNettyCallback?.receiveOrder(money, coins, startKey, unique)
//            if (coins.length > 0) {
//                val coin = coins.toInt()
//                val k = responseParam.k
//                if (k != null && coin > 0) {
//                    DBManager.getInstance().lyyOrderDao().getByK("0")
//                        .doOnSuccess(Consumer<List<LyyOrderEntity>> { lyyOrderEntities ->
//                            try {
//                                if (lyyOrderEntities != null && lyyOrderEntities.size > 0) {
//                                    val entity = lyyOrderEntities[0]
//                                    val selectPackages = entity.detail
//                                    if (selectPackages == null || selectPackages.size == 0) {
//                                        return@Consumer
//                                    }
//                                    val packageBean = selectPackages[0]
//                                    val outCoin = packageBean.value.toInt()
//                                    if (entity.success == 2 || outCoin != coin) {
//                                        //直接上报出币失败，退款
//                                        val param = EqStartResultParam()
//                                        param.uniqueCode = k
//                                        param.isSuccess = false
//                                        val channel =
//                                            packageBean.goodId + "," + packageBean.value + "," + packageBean.price
//                                        val strs: MutableList<String> = ArrayList()
//                                        strs.add(channel)
//                                        param.channels = strs
//                                        Logger.d("直接上报启动故障，退款：" + gson.toJson(param))
//                                        //                                MsgProducer.uploadEqStartResult();
//                                        val startEqParam = ReplyStartEqParam()
//                                        startEqParam.uniqueCode = responseParam.k
//                                        startEqParam.data = 1
//                                        startEqParam.failure = "页面超时"
//                                        MsgProducer.replyStartEq(startEqParam)
//                                        DBManager.deleteLyySelectPackage(k).subscribe()
//                                        return@Consumer
//                                    } else {
//                                        val startEqParam = ReplyStartEqParam()
//                                        startEqParam.uniqueCode = responseParam.k
//                                        startEqParam.data = 0
//                                        MsgProducer.replyStartEq(startEqParam)
//                                    }
//
//                                    //更新K到本地数据的orderNumber
//                                    entity.k = k
//                                    DBManager.getInstance().lyyOrderDao().update(entity)
//                                        .doOnSuccess {
//                                            val id = entity.id
//                                            val now = Date()
//                                            val orderEntity = OrderEntity()
//                                            orderEntity.date =
//                                                DateUtil.getDate(now)
//                                            orderEntity.time =
//                                                DateUtil.getDate2(now)
//                                            orderEntity.onDutyCode =
//                                                Constants.ONDUTY_CODE
//                                            orderEntity.orderNumber = k
//                                            orderEntity.success = 0
//                                            orderEntity.inCoin = 0
//                                            orderEntity.payType = entity.payType
//                                            orderEntity.outCoin = packageBean.value.toInt().toLong()
//                                            orderEntity.amount = packageBean.price
//                                            orderEntity.remainAmount =
//                                                id.toString() //乐摇摇平台，套餐id设置到orderEntity余额
//                                            orderEntity.accountRemainCoin = 0
////                                            mainActivity.receiveOrder(orderEntity, null)
//                                            onNettyCallback?.receiveOrder(orderEntity, null)
//                                        }.subscribe()
//                                } else {
//                                    Logger.d("本地数据未找到k=$startKey 的订单，直接退款")
//                                    val startEqParam = ReplyStartEqParam()
//                                    startEqParam.uniqueCode = responseParam.k
//                                    startEqParam.data = 1
//                                    startEqParam.failure = "页面超时"
//                                    MsgProducer.replyStartEq(startEqParam)
//                                    DBManager.deleteLyySelectPackage(k).subscribe()
//                                }
//                            } catch (e: Exception) {
//                                e.printStackTrace()
//                                Logger.e("lyy-收到支付结果 处理异常：" + e.message)
//                            }
//                        }).subscribe()
//                } else {
//                    Logger.d("其他异常情况：coin=$coin，直接退款")
//                    val startEqParam = ReplyStartEqParam()
//                    startEqParam.uniqueCode = responseParam.k
//                    startEqParam.data = 1
//                    startEqParam.failure = "页面超时"
//                    MsgProducer.replyStartEq(startEqParam)
//                    DBManager.deleteLyySelectPackage(k).subscribe()
//                }
//            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return true
    }

    /**
     *
     * @param responseParam
     * @param errorResp
     * @return
     */
    override fun errorHandler(responseParam: ResponseParam, errorResp: ErrorResp?): Boolean {
        // TODO Auto-generated method stub
        if (ActionCode.PQ.reCode == responseParam.a) {
            println("========" + Gson().toJson(responseParam))
        }
        return super.errorHandler(responseParam, errorResp)
    }

    /**
     * 检查设备
     * @param responseParam
     * @return
     */
    override fun checkEquipmentHandler(responseParam: ResponseParam): Boolean {
        super.checkEquipmentHandler(responseParam)
        try {
            val param = ReplyCheckEqParam()
            param.uniqueCode = responseParam.k
            param.data = 0
            param.failure = ""
            MsgProducer.replyCheckEq(param)
        } catch (e: Exception) {
            e.printStackTrace()
            Logger.e("checkEquipmentHandler 处理数据异常：" + e.message)
        }
        return true
    }

    /**
     * 获取套餐
     * @param responseParam
     * @return
     */
    override fun getRuleResult(responseParam: ResponseParam?): Boolean {
        super.getRuleResult(responseParam)
        try {
//            String packageStr = (String) responseParam.getP();
//            Log.d(TAG, "套餐数据：" + packageStr);
//            List<LyyPackageBean> lyyPackageBeans = GsonUtil.getInstance().fromJson(packageStr, new TypeToken<List<LyyPackageBean>>() {
//            }.getType());
            val lyyPackageBeans = getRespList(
                responseParam,
                LyySdkGoodBean::class.java
            ).apply {
                onNettyCallback?.refreshPackageData(this)
            }
//            if (lyyPackageBeans != null && lyyPackageBeans.size > 0) {
//                val goodBeanList: MutableList<GoodBean> = ArrayList()
//                for (lyyPackageBean in lyyPackageBeans) {
//                    val id = lyyPackageBean.id
//                    val name = lyyPackageBean.id
//                    val money = lyyPackageBean.money
//                    val amount = lyyPackageBean.amount
//                    val packageType = lyyPackageBean.type
//                    val created = lyyPackageBean.created
//                    val bean = GoodBean(
//                        id,
//                        money,
//                        amount,
//                        "0",
//                        name,
//                        "",
//                        money, packageType.toInt(),
//                        Constants.PLATFORM_LYY_SDK
//                    )
//                    bean.desc = created
//                    goodBeanList.add(bean)
//                }
//                if (goodBeanList.size < 1) {
//                    return true
//                }
//                //套餐数据持久化
//                val date = Date()
//                val entity = PackageEntity()
//                entity.date = DateUtil.getDate(date)
//                entity.time = DateUtil.getDate2(date)
//                entity.detail = goodBeanList
//                Logger.d("最终套餐数据:" + GsonUtil.getInstance().toJson(goodBeanList))
//                DBManager.insertPackage(entity).doOnSuccess { aLong ->
//                    Log.d(TAG, "插入套餐数据=$aLong")
//                    onNettyCallback?.refreshPackageData()
//                }.subscribe()
//            }
        } catch (e: Exception) {
            e.printStackTrace()
            Logger.e("getRuleResult 处理套餐数据异常：" + e.message)
        }
        return true
    }

    interface OnNettyCallback{
        /**
         * 登录成功
         * @param devNumber 设备号
         */
        fun onLoginSuccess(devNumber: String?)
        /**
         * 设备注册页面
         * @param show       0-显示 1-隐藏
         * @param registCode
         */
        fun showRegist(show: ShowType, registCode: String?)
        /**
         * 显示图片或二维码
         * @param qrCodeData
         * @param showType   0-二维码 1-图片
         */
        fun showPayCode(payCodeData: String?, showStyle: ShowStyle)

        /**
         * 收到订单
         * @param orderEntity 订单数据
         * @param other 其他数据
         */
//        fun receiveOrder(orderEntity: OrderEntity, other: String?)
        fun receiveOrder(money: String, coins: String, k: String, unique: String)

        /**
         * 刷新套餐数据
         * @param data 套餐数据
         */
        fun refreshPackageData(dataList: MutableList<LyySdkGoodBean>)

    }

}